
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>5. Kaleidoscope: Extending the Language: Control Flow &mdash; LLVM 3.7 documentation</title>
    
    <link rel="stylesheet" href="../_static/llvm-theme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.7',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="LLVM 3.7 documentation" href="../index.html" />
    <link rel="up" title="LLVM Tutorial: Table of Contents" href="index.html" />
    <link rel="next" title="6. Kaleidoscope: Extending the Language: User-defined Operators" href="LangImpl6.html" />
    <link rel="prev" title="4. Kaleidoscope: Adding JIT and Optimizer Support" href="LangImpl4.html" />
<style type="text/css">
  table.right { float: right; margin-left: 20px; }
  table.right td { border: 1px solid #ccc; }
</style>

  </head>
  <body role="document">
<div class="logo">
  <a href="../index.html">
    <img src="../_static/logo.png"
         alt="LLVM Logo" width="250" height="88"/></a>
</div>

    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="LangImpl6.html" title="6. Kaleidoscope: Extending the Language: User-defined Operators"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="LangImpl4.html" title="4. Kaleidoscope: Adding JIT and Optimizer Support"
             accesskey="P">previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">LLVM Tutorial: Table of Contents</a> &raquo;</li> 
      </ul>
    </div>


    <div class="document">
      <div class="documentwrapper">
          <div class="body" role="main">
            
  <div class="section" id="kaleidoscope-extending-the-language-control-flow">
<h1>5. Kaleidoscope: Extending the Language: Control Flow<a class="headerlink" href="#kaleidoscope-extending-the-language-control-flow" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#chapter-5-introduction" id="id2">Chapter 5 Introduction</a></li>
<li><a class="reference internal" href="#if-then-else" id="id3">If/Then/Else</a><ul>
<li><a class="reference internal" href="#lexer-extensions-for-if-then-else" id="id4">Lexer Extensions for If/Then/Else</a></li>
<li><a class="reference internal" href="#ast-extensions-for-if-then-else" id="id5">AST Extensions for If/Then/Else</a></li>
<li><a class="reference internal" href="#parser-extensions-for-if-then-else" id="id6">Parser Extensions for If/Then/Else</a></li>
<li><a class="reference internal" href="#llvm-ir-for-if-then-else" id="id7">LLVM IR for If/Then/Else</a></li>
<li><a class="reference internal" href="#code-generation-for-if-then-else" id="id8">Code Generation for If/Then/Else</a></li>
</ul>
</li>
<li><a class="reference internal" href="#for-loop-expression" id="id9">&#8216;for&#8217; Loop Expression</a><ul>
<li><a class="reference internal" href="#lexer-extensions-for-the-for-loop" id="id10">Lexer Extensions for the &#8216;for&#8217; Loop</a></li>
<li><a class="reference internal" href="#ast-extensions-for-the-for-loop" id="id11">AST Extensions for the &#8216;for&#8217; Loop</a></li>
<li><a class="reference internal" href="#parser-extensions-for-the-for-loop" id="id12">Parser Extensions for the &#8216;for&#8217; Loop</a></li>
<li><a class="reference internal" href="#llvm-ir-for-the-for-loop" id="id13">LLVM IR for the &#8216;for&#8217; Loop</a></li>
<li><a class="reference internal" href="#code-generation-for-the-for-loop" id="id14">Code Generation for the &#8216;for&#8217; Loop</a></li>
</ul>
</li>
<li><a class="reference internal" href="#full-code-listing" id="id15">Full Code Listing</a></li>
</ul>
</div>
<div class="section" id="chapter-5-introduction">
<h2><a class="toc-backref" href="#id2">5.1. Chapter 5 Introduction</a><a class="headerlink" href="#chapter-5-introduction" title="Permalink to this headline">¶</a></h2>
<p>Welcome to Chapter 5 of the &#8220;<a class="reference external" href="index.html">Implementing a language with
LLVM</a>&#8221; tutorial. Parts 1-4 described the implementation of
the simple Kaleidoscope language and included support for generating
LLVM IR, followed by optimizations and a JIT compiler. Unfortunately, as
presented, Kaleidoscope is mostly useless: it has no control flow other
than call and return. This means that you can&#8217;t have conditional
branches in the code, significantly limiting its power. In this episode
of &#8220;build that compiler&#8221;, we&#8217;ll extend Kaleidoscope to have an
if/then/else expression plus a simple &#8216;for&#8217; loop.</p>
</div>
<div class="section" id="if-then-else">
<h2><a class="toc-backref" href="#id3">5.2. If/Then/Else</a><a class="headerlink" href="#if-then-else" title="Permalink to this headline">¶</a></h2>
<p>Extending Kaleidoscope to support if/then/else is quite straightforward.
It basically requires adding support for this &#8220;new&#8221; concept to the
lexer, parser, AST, and LLVM code emitter. This example is nice, because
it shows how easy it is to &#8220;grow&#8221; a language over time, incrementally
extending it as new ideas are discovered.</p>
<p>Before we get going on &#8220;how&#8221; we add this extension, lets talk about
&#8220;what&#8221; we want. The basic idea is that we want to be able to write this
sort of thing:</p>
<div class="highlight-python"><div class="highlight"><pre>def fib(x)
  if x &lt; 3 then
    1
  else
    fib(x-1)+fib(x-2);
</pre></div>
</div>
<p>In Kaleidoscope, every construct is an expression: there are no
statements. As such, the if/then/else expression needs to return a value
like any other. Since we&#8217;re using a mostly functional form, we&#8217;ll have
it evaluate its conditional, then return the &#8216;then&#8217; or &#8216;else&#8217; value
based on how the condition was resolved. This is very similar to the C
&#8221;?:&#8221; expression.</p>
<p>The semantics of the if/then/else expression is that it evaluates the
condition to a boolean equality value: 0.0 is considered to be false and
everything else is considered to be true. If the condition is true, the
first subexpression is evaluated and returned, if the condition is
false, the second subexpression is evaluated and returned. Since
Kaleidoscope allows side-effects, this behavior is important to nail
down.</p>
<p>Now that we know what we &#8220;want&#8221;, lets break this down into its
constituent pieces.</p>
<div class="section" id="lexer-extensions-for-if-then-else">
<h3><a class="toc-backref" href="#id4">5.2.1. Lexer Extensions for If/Then/Else</a><a class="headerlink" href="#lexer-extensions-for-if-then-else" title="Permalink to this headline">¶</a></h3>
<p>The lexer extensions are straightforward. First we add new enum values
for the relevant tokens:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// control</span>
<span class="n">tok_if</span> <span class="o">=</span> <span class="o">-</span><span class="mi">6</span><span class="p">,</span> <span class="n">tok_then</span> <span class="o">=</span> <span class="o">-</span><span class="mi">7</span><span class="p">,</span> <span class="n">tok_else</span> <span class="o">=</span> <span class="o">-</span><span class="mi">8</span><span class="p">,</span>
</pre></div>
</div>
<p>Once we have that, we recognize the new keywords in the lexer. This is
pretty simple stuff:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="p">...</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;def&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_def</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;extern&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_extern</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;if&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_if</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;then&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_then</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;else&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_else</span><span class="p">;</span>
<span class="k">return</span> <span class="n">tok_identifier</span><span class="p">;</span>
</pre></div>
</div>
</div>
<div class="section" id="ast-extensions-for-if-then-else">
<h3><a class="toc-backref" href="#id5">5.2.2. AST Extensions for If/Then/Else</a><a class="headerlink" href="#ast-extensions-for-if-then-else" title="Permalink to this headline">¶</a></h3>
<p>To represent the new expression we add a new AST node for it:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">/// IfExprAST - Expression class for if/then/else.</span>
<span class="k">class</span> <span class="nc">IfExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Cond</span><span class="p">,</span> <span class="o">*</span><span class="n">Then</span><span class="p">,</span> <span class="o">*</span><span class="n">Else</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">IfExprAST</span><span class="p">(</span><span class="n">ExprAST</span> <span class="o">*</span><span class="n">cond</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">then</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">_else</span><span class="p">)</span>
    <span class="o">:</span> <span class="n">Cond</span><span class="p">(</span><span class="n">cond</span><span class="p">),</span> <span class="n">Then</span><span class="p">(</span><span class="n">then</span><span class="p">),</span> <span class="n">Else</span><span class="p">(</span><span class="n">_else</span><span class="p">)</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">();</span>
<span class="p">};</span>
</pre></div>
</div>
<p>The AST node just has pointers to the various subexpressions.</p>
</div>
<div class="section" id="parser-extensions-for-if-then-else">
<h3><a class="toc-backref" href="#id6">5.2.3. Parser Extensions for If/Then/Else</a><a class="headerlink" href="#parser-extensions-for-if-then-else" title="Permalink to this headline">¶</a></h3>
<p>Now that we have the relevant tokens coming from the lexer and we have
the AST node to build, our parsing logic is relatively straightforward.
First we define a new parsing function:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">/// ifexpr ::= &#39;if&#39; expression &#39;then&#39; expression &#39;else&#39; expression</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseIfExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat the if.</span>

  <span class="c1">// condition.</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Cond</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">Cond</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_then</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected then&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat the then</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Then</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Then</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_else</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected else&quot;</span><span class="p">);</span>

  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Else</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">Else</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">return</span> <span class="k">new</span> <span class="n">IfExprAST</span><span class="p">(</span><span class="n">Cond</span><span class="p">,</span> <span class="n">Then</span><span class="p">,</span> <span class="n">Else</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Next we hook it up as a primary expression:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParsePrimary</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">switch</span> <span class="p">(</span><span class="n">CurTok</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">default</span><span class="o">:</span> <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;unknown token when expecting an expression&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="nl">tok_identifier</span><span class="p">:</span> <span class="k">return</span> <span class="n">ParseIdentifierExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="nl">tok_number</span><span class="p">:</span>     <span class="k">return</span> <span class="n">ParseNumberExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="sc">&#39;(&#39;</span><span class="o">:</span>            <span class="k">return</span> <span class="n">ParseParenExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="nl">tok_if</span><span class="p">:</span>         <span class="k">return</span> <span class="n">ParseIfExpr</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="llvm-ir-for-if-then-else">
<h3><a class="toc-backref" href="#id7">5.2.4. LLVM IR for If/Then/Else</a><a class="headerlink" href="#llvm-ir-for-if-then-else" title="Permalink to this headline">¶</a></h3>
<p>Now that we have it parsing and building the AST, the final piece is
adding LLVM code generation support. This is the most interesting part
of the if/then/else example, because this is where it starts to
introduce new concepts. All of the code above has been thoroughly
described in previous chapters.</p>
<p>To motivate the code we want to produce, lets take a look at a simple
example. Consider:</p>
<div class="highlight-python"><div class="highlight"><pre>extern foo();
extern bar();
def baz(x) if x then foo() else bar();
</pre></div>
</div>
<p>If you disable optimizations, the code you&#8217;ll (soon) get from
Kaleidoscope looks like this:</p>
<div class="highlight-llvm"><div class="highlight"><pre><span class="k">declare</span> <span class="kt">double</span> <span class="vg">@foo</span><span class="p">()</span>

<span class="k">declare</span> <span class="kt">double</span> <span class="vg">@bar</span><span class="p">()</span>

<span class="k">define</span> <span class="kt">double</span> <span class="vg">@baz</span><span class="p">(</span><span class="kt">double</span> <span class="nv">%x</span><span class="p">)</span> <span class="p">{</span>
<span class="nl">entry:</span>
  <span class="nv">%ifcond</span> <span class="p">=</span> <span class="k">fcmp</span> <span class="k">one</span> <span class="kt">double</span> <span class="nv">%x</span><span class="p">,</span> <span class="m">0.000000e+00</span>
  <span class="k">br</span> <span class="k">i1</span> <span class="nv">%ifcond</span><span class="p">,</span> <span class="kt">label</span> <span class="nv">%then</span><span class="p">,</span> <span class="kt">label</span> <span class="nv">%else</span>

<span class="nl">then:</span>       <span class="c">; preds = %entry</span>
  <span class="nv">%calltmp</span> <span class="p">=</span> <span class="k">call</span> <span class="kt">double</span> <span class="vg">@foo</span><span class="p">()</span>
  <span class="k">br</span> <span class="kt">label</span> <span class="nv">%ifcont</span>

<span class="nl">else:</span>       <span class="c">; preds = %entry</span>
  <span class="nv">%calltmp1</span> <span class="p">=</span> <span class="k">call</span> <span class="kt">double</span> <span class="vg">@bar</span><span class="p">()</span>
  <span class="k">br</span> <span class="kt">label</span> <span class="nv">%ifcont</span>

<span class="nl">ifcont:</span>     <span class="c">; preds = %else, %then</span>
  <span class="nv">%iftmp</span> <span class="p">=</span> <span class="k">phi</span> <span class="kt">double</span> <span class="p">[</span> <span class="nv">%calltmp</span><span class="p">,</span> <span class="nv">%then</span> <span class="p">],</span> <span class="p">[</span> <span class="nv">%calltmp1</span><span class="p">,</span> <span class="nv">%else</span> <span class="p">]</span>
  <span class="k">ret</span> <span class="kt">double</span> <span class="nv">%iftmp</span>
<span class="p">}</span>
</pre></div>
</div>
<p>To visualize the control flow graph, you can use a nifty feature of the
LLVM &#8216;<a class="reference external" href="http://llvm.org/cmds/opt.html">opt</a>&#8216; tool. If you put this LLVM
IR into &#8220;t.ll&#8221; and run &#8220;<code class="docutils literal"><span class="pre">llvm-as</span> <span class="pre">&lt;</span> <span class="pre">t.ll</span> <span class="pre">|</span> <span class="pre">opt</span> <span class="pre">-analyze</span> <span class="pre">-view-cfg</span></code>&#8221;, <a class="reference external" href="../ProgrammersManual.html#ViewGraph">a
window will pop up</a> and you&#8217;ll
see this graph:</p>
<div class="figure align-center" id="id1">
<img alt="Example CFG" src="../_images/LangImpl5-cfg.png" />
<p class="caption"><span class="caption-text">Example CFG</span></p>
</div>
<p>Another way to get this is to call &#8220;<code class="docutils literal"><span class="pre">F-&gt;viewCFG()</span></code>&#8221; or
&#8220;<code class="docutils literal"><span class="pre">F-&gt;viewCFGOnly()</span></code>&#8221; (where F is a &#8220;<code class="docutils literal"><span class="pre">Function*</span></code>&#8221;) either by
inserting actual calls into the code and recompiling or by calling these
in the debugger. LLVM has many nice features for visualizing various
graphs.</p>
<p>Getting back to the generated code, it is fairly simple: the entry block
evaluates the conditional expression (&#8220;x&#8221; in our case here) and compares
the result to 0.0 with the &#8220;<code class="docutils literal"><span class="pre">fcmp</span> <span class="pre">one</span></code>&#8221; instruction (&#8216;one&#8217; is &#8220;Ordered
and Not Equal&#8221;). Based on the result of this expression, the code jumps
to either the &#8220;then&#8221; or &#8220;else&#8221; blocks, which contain the expressions for
the true/false cases.</p>
<p>Once the then/else blocks are finished executing, they both branch back
to the &#8216;ifcont&#8217; block to execute the code that happens after the
if/then/else. In this case the only thing left to do is to return to the
caller of the function. The question then becomes: how does the code
know which expression to return?</p>
<p>The answer to this question involves an important SSA operation: the
<a class="reference external" href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Phi
operation</a>.
If you&#8217;re not familiar with SSA, <a class="reference external" href="http://en.wikipedia.org/wiki/Static_single_assignment_form">the wikipedia
article</a>
is a good introduction and there are various other introductions to it
available on your favorite search engine. The short version is that
&#8220;execution&#8221; of the Phi operation requires &#8220;remembering&#8221; which block
control came from. The Phi operation takes on the value corresponding to
the input control block. In this case, if control comes in from the
&#8220;then&#8221; block, it gets the value of &#8220;calltmp&#8221;. If control comes from the
&#8220;else&#8221; block, it gets the value of &#8220;calltmp1&#8221;.</p>
<p>At this point, you are probably starting to think &#8220;Oh no! This means my
simple and elegant front-end will have to start generating SSA form in
order to use LLVM!&#8221;. Fortunately, this is not the case, and we strongly
advise <em>not</em> implementing an SSA construction algorithm in your
front-end unless there is an amazingly good reason to do so. In
practice, there are two sorts of values that float around in code
written for your average imperative programming language that might need
Phi nodes:</p>
<ol class="arabic simple">
<li>Code that involves user variables: <code class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">x</span> <span class="pre">=</span> <span class="pre">x</span> <span class="pre">+</span> <span class="pre">1;</span></code></li>
<li>Values that are implicit in the structure of your AST, such as the
Phi node in this case.</li>
</ol>
<p>In <a class="reference external" href="LangImpl7.html">Chapter 7</a> of this tutorial (&#8220;mutable variables&#8221;),
we&#8217;ll talk about #1 in depth. For now, just believe me that you don&#8217;t
need SSA construction to handle this case. For #2, you have the choice
of using the techniques that we will describe for #1, or you can insert
Phi nodes directly, if convenient. In this case, it is really
easy to generate the Phi node, so we choose to do it directly.</p>
<p>Okay, enough of the motivation and overview, lets generate code!</p>
</div>
<div class="section" id="code-generation-for-if-then-else">
<h3><a class="toc-backref" href="#id8">5.2.5. Code Generation for If/Then/Else</a><a class="headerlink" href="#code-generation-for-if-then-else" title="Permalink to this headline">¶</a></h3>
<p>In order to generate code for this, we implement the <code class="docutils literal"><span class="pre">Codegen</span></code> method
for <code class="docutils literal"><span class="pre">IfExprAST</span></code>:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Value</span> <span class="o">*</span><span class="n">IfExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">CondV</span> <span class="o">=</span> <span class="n">Cond</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CondV</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// Convert condition to a bool by comparing equal to 0.0.</span>
  <span class="n">CondV</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpONE</span><span class="p">(</span><span class="n">CondV</span><span class="p">,</span>
                              <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="mf">0.0</span><span class="p">)),</span>
                                <span class="s">&quot;ifcond&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>This code is straightforward and similar to what we saw before. We emit
the expression for the condition, then compare that value to zero to get
a truth value as a 1-bit (bool) value.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">()</span><span class="o">-&gt;</span><span class="n">getParent</span><span class="p">();</span>

<span class="c1">// Create blocks for the then and else cases.  Insert the &#39;then&#39; block at the</span>
<span class="c1">// end of the function.</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">ThenBB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;then&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">ElseBB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;else&quot;</span><span class="p">);</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">MergeBB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;ifcont&quot;</span><span class="p">);</span>

<span class="n">Builder</span><span class="p">.</span><span class="n">CreateCondBr</span><span class="p">(</span><span class="n">CondV</span><span class="p">,</span> <span class="n">ThenBB</span><span class="p">,</span> <span class="n">ElseBB</span><span class="p">);</span>
</pre></div>
</div>
<p>This code creates the basic blocks that are related to the if/then/else
statement, and correspond directly to the blocks in the example above.
The first line gets the current Function object that is being built. It
gets this by asking the builder for the current BasicBlock, and asking
that block for its &#8220;parent&#8221; (the function it is currently embedded
into).</p>
<p>Once it has that, it creates three blocks. Note that it passes
&#8220;TheFunction&#8221; into the constructor for the &#8220;then&#8221; block. This causes the
constructor to automatically insert the new block into the end of the
specified function. The other two blocks are created, but aren&#8217;t yet
inserted into the function.</p>
<p>Once the blocks are created, we can emit the conditional branch that
chooses between them. Note that creating new blocks does not implicitly
affect the IRBuilder, so it is still inserting into the block that the
condition went into. Also note that it is creating a branch to the
&#8220;then&#8221; block and the &#8220;else&#8221; block, even though the &#8220;else&#8221; block isn&#8217;t
inserted into the function yet. This is all ok: it is the standard way
that LLVM supports forward references.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Emit then value.</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">ThenBB</span><span class="p">);</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">ThenV</span> <span class="o">=</span> <span class="n">Then</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">ThenV</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

<span class="n">Builder</span><span class="p">.</span><span class="n">CreateBr</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
<span class="c1">// Codegen of &#39;Then&#39; can change the current block, update ThenBB for the PHI.</span>
<span class="n">ThenBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>
</pre></div>
</div>
<p>After the conditional branch is inserted, we move the builder to start
inserting into the &#8220;then&#8221; block. Strictly speaking, this call moves the
insertion point to be at the end of the specified block. However, since
the &#8220;then&#8221; block is empty, it also starts out by inserting at the
beginning of the block. :)</p>
<p>Once the insertion point is set, we recursively codegen the &#8220;then&#8221;
expression from the AST. To finish off the &#8220;then&#8221; block, we create an
unconditional branch to the merge block. One interesting (and very
important) aspect of the LLVM IR is that it <a class="reference external" href="../LangRef.html#functionstructure">requires all basic blocks
to be &#8220;terminated&#8221;</a> with a <a class="reference external" href="../LangRef.html#terminators">control
flow instruction</a> such as return or
branch. This means that all control flow, <em>including fall throughs</em> must
be made explicit in the LLVM IR. If you violate this rule, the verifier
will emit an error.</p>
<p>The final line here is quite subtle, but is very important. The basic
issue is that when we create the Phi node in the merge block, we need to
set up the block/value pairs that indicate how the Phi will work.
Importantly, the Phi node expects to have an entry for each predecessor
of the block in the CFG. Why then, are we getting the current block when
we just set it to ThenBB 5 lines above? The problem is that the &#8220;Then&#8221;
expression may actually itself change the block that the Builder is
emitting into if, for example, it contains a nested &#8220;if/then/else&#8221;
expression. Because calling Codegen recursively could arbitrarily change
the notion of the current block, we are required to get an up-to-date
value for code that will set up the Phi node.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Emit else block.</span>
<span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">getBasicBlockList</span><span class="p">().</span><span class="n">push_back</span><span class="p">(</span><span class="n">ElseBB</span><span class="p">);</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">ElseBB</span><span class="p">);</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">ElseV</span> <span class="o">=</span> <span class="n">Else</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">ElseV</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

<span class="n">Builder</span><span class="p">.</span><span class="n">CreateBr</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
<span class="c1">// Codegen of &#39;Else&#39; can change the current block, update ElseBB for the PHI.</span>
<span class="n">ElseBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>
</pre></div>
</div>
<p>Code generation for the &#8216;else&#8217; block is basically identical to codegen
for the &#8216;then&#8217; block. The only significant difference is the first line,
which adds the &#8216;else&#8217; block to the function. Recall previously that the
&#8216;else&#8217; block was created, but not added to the function. Now that the
&#8216;then&#8217; and &#8216;else&#8217; blocks are emitted, we can finish up with the merge
code:</p>
<div class="highlight-c++"><div class="highlight"><pre>  <span class="c1">// Emit merge block.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">getBasicBlockList</span><span class="p">().</span><span class="n">push_back</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
  <span class="n">PHINode</span> <span class="o">*</span><span class="n">PN</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreatePHI</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span> <span class="mi">2</span><span class="p">,</span>
                                  <span class="s">&quot;iftmp&quot;</span><span class="p">);</span>

  <span class="n">PN</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">ThenV</span><span class="p">,</span> <span class="n">ThenBB</span><span class="p">);</span>
  <span class="n">PN</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">ElseV</span><span class="p">,</span> <span class="n">ElseBB</span><span class="p">);</span>
  <span class="k">return</span> <span class="n">PN</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The first two lines here are now familiar: the first adds the &#8220;merge&#8221;
block to the Function object (it was previously floating, like the else
block above). The second changes the insertion point so that newly
created code will go into the &#8220;merge&#8221; block. Once that is done, we need
to create the PHI node and set up the block/value pairs for the PHI.</p>
<p>Finally, the CodeGen function returns the phi node as the value computed
by the if/then/else expression. In our example above, this returned
value will feed into the code for the top-level function, which will
create the return instruction.</p>
<p>Overall, we now have the ability to execute conditional code in
Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
language that can calculate a wide variety of numeric functions. Next up
we&#8217;ll add another useful expression that is familiar from non-functional
languages...</p>
</div>
</div>
<div class="section" id="for-loop-expression">
<h2><a class="toc-backref" href="#id9">5.3. &#8216;for&#8217; Loop Expression</a><a class="headerlink" href="#for-loop-expression" title="Permalink to this headline">¶</a></h2>
<p>Now that we know how to add basic control flow constructs to the
language, we have the tools to add more powerful things. Lets add
something more aggressive, a &#8216;for&#8217; expression:</p>
<div class="highlight-python"><div class="highlight"><pre>extern putchard(char)
def printstar(n)
  for i = 1, i &lt; n, 1.0 in
    putchard(42);  # ascii 42 = &#39;*&#39;

# print 100 &#39;*&#39; characters
printstar(100);
</pre></div>
</div>
<p>This expression defines a new variable (&#8220;i&#8221; in this case) which iterates
from a starting value, while the condition (&#8220;i &lt; n&#8221; in this case) is
true, incrementing by an optional step value (&#8220;1.0&#8221; in this case). If
the step value is omitted, it defaults to 1.0. While the loop is true,
it executes its body expression. Because we don&#8217;t have anything better
to return, we&#8217;ll just define the loop as always returning 0.0. In the
future when we have mutable variables, it will get more useful.</p>
<p>As before, lets talk about the changes that we need to Kaleidoscope to
support this.</p>
<div class="section" id="lexer-extensions-for-the-for-loop">
<h3><a class="toc-backref" href="#id10">5.3.1. Lexer Extensions for the &#8216;for&#8217; Loop</a><a class="headerlink" href="#lexer-extensions-for-the-for-loop" title="Permalink to this headline">¶</a></h3>
<p>The lexer extensions are the same sort of thing as for if/then/else:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="p">...</span> <span class="n">in</span> <span class="k">enum</span> <span class="n">Token</span> <span class="p">...</span>
<span class="c1">// control</span>
<span class="n">tok_if</span> <span class="o">=</span> <span class="o">-</span><span class="mi">6</span><span class="p">,</span> <span class="n">tok_then</span> <span class="o">=</span> <span class="o">-</span><span class="mi">7</span><span class="p">,</span> <span class="n">tok_else</span> <span class="o">=</span> <span class="o">-</span><span class="mi">8</span><span class="p">,</span>
<span class="n">tok_for</span> <span class="o">=</span> <span class="o">-</span><span class="mi">9</span><span class="p">,</span> <span class="n">tok_in</span> <span class="o">=</span> <span class="o">-</span><span class="mi">10</span>

<span class="p">...</span> <span class="n">in</span> <span class="n">gettok</span> <span class="p">...</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;def&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_def</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;extern&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_extern</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;if&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_if</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;then&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_then</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;else&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_else</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;for&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_for</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;in&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_in</span><span class="p">;</span>
<span class="k">return</span> <span class="n">tok_identifier</span><span class="p">;</span>
</pre></div>
</div>
</div>
<div class="section" id="ast-extensions-for-the-for-loop">
<h3><a class="toc-backref" href="#id11">5.3.2. AST Extensions for the &#8216;for&#8217; Loop</a><a class="headerlink" href="#ast-extensions-for-the-for-loop" title="Permalink to this headline">¶</a></h3>
<p>The AST node is just as simple. It basically boils down to capturing the
variable name and the constituent expressions in the node.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">/// ForExprAST - Expression class for for/in.</span>
<span class="k">class</span> <span class="nc">ForExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">VarName</span><span class="p">;</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Start</span><span class="p">,</span> <span class="o">*</span><span class="n">End</span><span class="p">,</span> <span class="o">*</span><span class="n">Step</span><span class="p">,</span> <span class="o">*</span><span class="n">Body</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">ForExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">varname</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">start</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">end</span><span class="p">,</span>
             <span class="n">ExprAST</span> <span class="o">*</span><span class="n">step</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">body</span><span class="p">)</span>
    <span class="o">:</span> <span class="n">VarName</span><span class="p">(</span><span class="n">varname</span><span class="p">),</span> <span class="n">Start</span><span class="p">(</span><span class="n">start</span><span class="p">),</span> <span class="n">End</span><span class="p">(</span><span class="n">end</span><span class="p">),</span> <span class="n">Step</span><span class="p">(</span><span class="n">step</span><span class="p">),</span> <span class="n">Body</span><span class="p">(</span><span class="n">body</span><span class="p">)</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">();</span>
<span class="p">};</span>
</pre></div>
</div>
</div>
<div class="section" id="parser-extensions-for-the-for-loop">
<h3><a class="toc-backref" href="#id12">5.3.3. Parser Extensions for the &#8216;for&#8217; Loop</a><a class="headerlink" href="#parser-extensions-for-the-for-loop" title="Permalink to this headline">¶</a></h3>
<p>The parser code is also fairly standard. The only interesting thing here
is handling of the optional step value. The parser code handles it by
checking to see if the second comma is present. If not, it sets the step
value to null in the AST node:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">/// forexpr ::= &#39;for&#39; identifier &#39;=&#39; expr &#39;,&#39; expr (&#39;,&#39; expr)? &#39;in&#39; expression</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseForExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat the for.</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected identifier after for&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat identifier.</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;=&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;=&#39; after for&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat &#39;=&#39;.</span>


  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Start</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Start</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;,&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;,&#39; after for start value&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">End</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">End</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// The step value is optional.</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Step</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">==</span> <span class="sc">&#39;,&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">getNextToken</span><span class="p">();</span>
    <span class="n">Step</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Step</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_in</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;in&#39; after for&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat &#39;in&#39;.</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Body</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Body</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">return</span> <span class="k">new</span> <span class="n">ForExprAST</span><span class="p">(</span><span class="n">IdName</span><span class="p">,</span> <span class="n">Start</span><span class="p">,</span> <span class="n">End</span><span class="p">,</span> <span class="n">Step</span><span class="p">,</span> <span class="n">Body</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="llvm-ir-for-the-for-loop">
<h3><a class="toc-backref" href="#id13">5.3.4. LLVM IR for the &#8216;for&#8217; Loop</a><a class="headerlink" href="#llvm-ir-for-the-for-loop" title="Permalink to this headline">¶</a></h3>
<p>Now we get to the good part: the LLVM IR we want to generate for this
thing. With the simple example above, we get this LLVM IR (note that
this dump is generated with optimizations disabled for clarity):</p>
<div class="highlight-llvm"><div class="highlight"><pre><span class="k">declare</span> <span class="kt">double</span> <span class="vg">@putchard</span><span class="p">(</span><span class="kt">double</span><span class="p">)</span>

<span class="k">define</span> <span class="kt">double</span> <span class="vg">@printstar</span><span class="p">(</span><span class="kt">double</span> <span class="nv">%n</span><span class="p">)</span> <span class="p">{</span>
<span class="nl">entry:</span>
  <span class="c">; initial value = 1.0 (inlined into phi)</span>
  <span class="k">br</span> <span class="kt">label</span> <span class="nv">%loop</span>

<span class="nl">loop:</span>       <span class="c">; preds = %loop, %entry</span>
  <span class="nv">%i</span> <span class="p">=</span> <span class="k">phi</span> <span class="kt">double</span> <span class="p">[</span> <span class="m">1.000000e+00</span><span class="p">,</span> <span class="nv">%entry</span> <span class="p">],</span> <span class="p">[</span> <span class="nv">%nextvar</span><span class="p">,</span> <span class="nv">%loop</span> <span class="p">]</span>
  <span class="c">; body</span>
  <span class="nv">%calltmp</span> <span class="p">=</span> <span class="k">call</span> <span class="kt">double</span> <span class="vg">@putchard</span><span class="p">(</span><span class="kt">double</span> <span class="m">4.200000e+01</span><span class="p">)</span>
  <span class="c">; increment</span>
  <span class="nv">%nextvar</span> <span class="p">=</span> <span class="k">fadd</span> <span class="kt">double</span> <span class="nv">%i</span><span class="p">,</span> <span class="m">1.000000e+00</span>

  <span class="c">; termination test</span>
  <span class="nv">%cmptmp</span> <span class="p">=</span> <span class="k">fcmp</span> <span class="k">ult</span> <span class="kt">double</span> <span class="nv">%i</span><span class="p">,</span> <span class="nv">%n</span>
  <span class="nv">%booltmp</span> <span class="p">=</span> <span class="k">uitofp</span> <span class="k">i1</span> <span class="nv">%cmptmp</span> <span class="k">to</span> <span class="kt">double</span>
  <span class="nv">%loopcond</span> <span class="p">=</span> <span class="k">fcmp</span> <span class="k">one</span> <span class="kt">double</span> <span class="nv">%booltmp</span><span class="p">,</span> <span class="m">0.000000e+00</span>
  <span class="k">br</span> <span class="k">i1</span> <span class="nv">%loopcond</span><span class="p">,</span> <span class="kt">label</span> <span class="nv">%loop</span><span class="p">,</span> <span class="kt">label</span> <span class="nv">%afterloop</span>

<span class="nl">afterloop:</span>      <span class="c">; preds = %loop</span>
  <span class="c">; loop always returns 0.0</span>
  <span class="k">ret</span> <span class="kt">double</span> <span class="m">0.000000e+00</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This loop contains all the same constructs we saw before: a phi node,
several expressions, and some basic blocks. Lets see how this fits
together.</p>
</div>
<div class="section" id="code-generation-for-the-for-loop">
<h3><a class="toc-backref" href="#id14">5.3.5. Code Generation for the &#8216;for&#8217; Loop</a><a class="headerlink" href="#code-generation-for-the-for-loop" title="Permalink to this headline">¶</a></h3>
<p>The first part of Codegen is very simple: we just output the start
expression for the loop value:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Value</span> <span class="o">*</span><span class="n">ForExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Emit the start code first, without &#39;variable&#39; in scope.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">StartVal</span> <span class="o">=</span> <span class="n">Start</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">StartVal</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</pre></div>
</div>
<p>With this out of the way, the next step is to set up the LLVM basic
block for the start of the loop body. In the case above, the whole loop
body is one block, but remember that the body code itself could consist
of multiple blocks (e.g. if it contains an if/then/else or a for/in
expression).</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Make the new basic block for the loop header, inserting after current</span>
<span class="c1">// block.</span>
<span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">()</span><span class="o">-&gt;</span><span class="n">getParent</span><span class="p">();</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">PreheaderBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">LoopBB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;loop&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>

<span class="c1">// Insert an explicit fall through from the current block to the LoopBB.</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">CreateBr</span><span class="p">(</span><span class="n">LoopBB</span><span class="p">);</span>
</pre></div>
</div>
<p>This code is similar to what we saw for if/then/else. Because we will
need it to create the Phi node, we remember the block that falls through
into the loop. Once we have that, we create the actual block that starts
the loop and create an unconditional branch for the fall-through between
the two blocks.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Start insertion in LoopBB.</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">LoopBB</span><span class="p">);</span>

<span class="c1">// Start the PHI node with an entry for Start.</span>
<span class="n">PHINode</span> <span class="o">*</span><span class="n">Variable</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreatePHI</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span> <span class="mi">2</span><span class="p">,</span> <span class="n">VarName</span><span class="p">.</span><span class="n">c_str</span><span class="p">());</span>
<span class="n">Variable</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">StartVal</span><span class="p">,</span> <span class="n">PreheaderBB</span><span class="p">);</span>
</pre></div>
</div>
<p>Now that the &#8220;preheader&#8221; for the loop is set up, we switch to emitting
code for the loop body. To begin with, we move the insertion point and
create the PHI node for the loop induction variable. Since we already
know the incoming value for the starting value, we add it to the Phi
node. Note that the Phi will eventually get a second value for the
backedge, but we can&#8217;t set it up yet (because it doesn&#8217;t exist!).</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Within the loop, the variable is defined equal to the PHI node.  If it</span>
<span class="c1">// shadows an existing variable, we have to restore it, so save it now.</span>
<span class="n">Value</span> <span class="o">*</span><span class="n">OldVal</span> <span class="o">=</span> <span class="n">NamedValues</span><span class="p">[</span><span class="n">VarName</span><span class="p">];</span>
<span class="n">NamedValues</span><span class="p">[</span><span class="n">VarName</span><span class="p">]</span> <span class="o">=</span> <span class="n">Variable</span><span class="p">;</span>

<span class="c1">// Emit the body of the loop.  This, like any other expr, can change the</span>
<span class="c1">// current BB.  Note that we ignore the value computed by the body, but don&#39;t</span>
<span class="c1">// allow an error.</span>
<span class="k">if</span> <span class="p">(</span><span class="n">Body</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">()</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</pre></div>
</div>
<p>Now the code starts to get more interesting. Our &#8216;for&#8217; loop introduces a
new variable to the symbol table. This means that our symbol table can
now contain either function arguments or loop variables. To handle this,
before we codegen the body of the loop, we add the loop variable as the
current value for its name. Note that it is possible that there is a
variable of the same name in the outer scope. It would be easy to make
this an error (emit an error and return null if there is already an
entry for VarName) but we choose to allow shadowing of variables. In
order to handle this correctly, we remember the Value that we are
potentially shadowing in <code class="docutils literal"><span class="pre">OldVal</span></code> (which will be null if there is no
shadowed variable).</p>
<p>Once the loop variable is set into the symbol table, the code
recursively codegen&#8217;s the body. This allows the body to use the loop
variable: any references to it will naturally find it in the symbol
table.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Emit the step value.</span>
<span class="n">Value</span> <span class="o">*</span><span class="n">StepVal</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">Step</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">StepVal</span> <span class="o">=</span> <span class="n">Step</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">StepVal</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
  <span class="c1">// If not specified, use 1.0.</span>
  <span class="n">StepVal</span> <span class="o">=</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="mf">1.0</span><span class="p">));</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">NextVar</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFAdd</span><span class="p">(</span><span class="n">Variable</span><span class="p">,</span> <span class="n">StepVal</span><span class="p">,</span> <span class="s">&quot;nextvar&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>Now that the body is emitted, we compute the next value of the iteration
variable by adding the step value, or 1.0 if it isn&#8217;t present.
&#8216;<code class="docutils literal"><span class="pre">NextVar</span></code>&#8216; will be the value of the loop variable on the next
iteration of the loop.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Compute the end condition.</span>
<span class="n">Value</span> <span class="o">*</span><span class="n">EndCond</span> <span class="o">=</span> <span class="n">End</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">EndCond</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="n">EndCond</span><span class="p">;</span>

<span class="c1">// Convert condition to a bool by comparing equal to 0.0.</span>
<span class="n">EndCond</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpONE</span><span class="p">(</span><span class="n">EndCond</span><span class="p">,</span>
                            <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="mf">0.0</span><span class="p">)),</span>
                                <span class="s">&quot;loopcond&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>Finally, we evaluate the exit value of the loop, to determine whether
the loop should exit. This mirrors the condition evaluation for the
if/then/else statement.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Create the &quot;after loop&quot; block and insert it.</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">LoopEndBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">AfterBB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;afterloop&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>

<span class="c1">// Insert the conditional branch into the end of LoopEndBB.</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">CreateCondBr</span><span class="p">(</span><span class="n">EndCond</span><span class="p">,</span> <span class="n">LoopBB</span><span class="p">,</span> <span class="n">AfterBB</span><span class="p">);</span>

<span class="c1">// Any new code will be inserted in AfterBB.</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">AfterBB</span><span class="p">);</span>
</pre></div>
</div>
<p>With the code for the body of the loop complete, we just need to finish
up the control flow for it. This code remembers the end block (for the
phi node), then creates the block for the loop exit (&#8220;afterloop&#8221;). Based
on the value of the exit condition, it creates a conditional branch that
chooses between executing the loop again and exiting the loop. Any
future code is emitted in the &#8220;afterloop&#8221; block, so it sets the
insertion position to it.</p>
<div class="highlight-c++"><div class="highlight"><pre>  <span class="c1">// Add a new entry to the PHI node for the backedge.</span>
  <span class="n">Variable</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">NextVar</span><span class="p">,</span> <span class="n">LoopEndBB</span><span class="p">);</span>

  <span class="c1">// Restore the unshadowed variable.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">OldVal</span><span class="p">)</span>
    <span class="n">NamedValues</span><span class="p">[</span><span class="n">VarName</span><span class="p">]</span> <span class="o">=</span> <span class="n">OldVal</span><span class="p">;</span>
  <span class="k">else</span>
    <span class="n">NamedValues</span><span class="p">.</span><span class="n">erase</span><span class="p">(</span><span class="n">VarName</span><span class="p">);</span>

  <span class="c1">// for expr always returns 0.0.</span>
  <span class="k">return</span> <span class="n">Constant</span><span class="o">::</span><span class="n">getNullValue</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()));</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The final code handles various cleanups: now that we have the &#8220;NextVar&#8221;
value, we can add the incoming value to the loop PHI node. After that,
we remove the loop variable from the symbol table, so that it isn&#8217;t in
scope after the for loop. Finally, code generation of the for loop
always returns 0.0, so that is what we return from
<code class="docutils literal"><span class="pre">ForExprAST::Codegen</span></code>.</p>
<p>With this, we conclude the &#8220;adding control flow to Kaleidoscope&#8221; chapter
of the tutorial. In this chapter we added two control flow constructs,
and used them to motivate a couple of aspects of the LLVM IR that are
important for front-end implementors to know. In the next chapter of our
saga, we will get a bit crazier and add <a class="reference external" href="LangImpl6.html">user-defined
operators</a> to our poor innocent language.</p>
</div>
</div>
<div class="section" id="full-code-listing">
<h2><a class="toc-backref" href="#id15">5.4. Full Code Listing</a><a class="headerlink" href="#full-code-listing" title="Permalink to this headline">¶</a></h2>
<p>Here is the complete code listing for our running example, enhanced with
the if/then/else and for expressions.. To build this example, use:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="c"># Compile</span>
clang++ -g toy.cpp <span class="sb">`</span>llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native<span class="sb">`</span> -O3 -o toy
<span class="c"># Run</span>
./toy
</pre></div>
</div>
<p>Here is the code:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="cp">#include &quot;llvm/ADT/STLExtras.h&quot;</span>
<span class="cp">#include &quot;llvm/Analysis/Passes.h&quot;</span>
<span class="cp">#include &quot;llvm/ExecutionEngine/ExecutionEngine.h&quot;</span>
<span class="cp">#include &quot;llvm/ExecutionEngine/MCJIT.h&quot;</span>
<span class="cp">#include &quot;llvm/ExecutionEngine/SectionMemoryManager.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/DataLayout.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/DerivedTypes.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/IRBuilder.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/LLVMContext.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/LegacyPassManager.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/Module.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/Verifier.h&quot;</span>
<span class="cp">#include &quot;llvm/Support/TargetSelect.h&quot;</span>
<span class="cp">#include &quot;llvm/Transforms/Scalar.h&quot;</span>
<span class="cp">#include &lt;cctype&gt;</span>
<span class="cp">#include &lt;cstdio&gt;</span>
<span class="cp">#include &lt;map&gt;</span>
<span class="cp">#include &lt;string&gt;</span>
<span class="cp">#include &lt;vector&gt;</span>
<span class="k">using</span> <span class="k">namespace</span> <span class="n">llvm</span><span class="p">;</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Lexer</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">// The lexer returns tokens [0-255] if it is an unknown character, otherwise one</span>
<span class="c1">// of these for known things.</span>
<span class="k">enum</span> <span class="n">Token</span> <span class="p">{</span>
  <span class="n">tok_eof</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span>

  <span class="c1">// commands</span>
  <span class="n">tok_def</span> <span class="o">=</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span>
  <span class="n">tok_extern</span> <span class="o">=</span> <span class="o">-</span><span class="mi">3</span><span class="p">,</span>

  <span class="c1">// primary</span>
  <span class="n">tok_identifier</span> <span class="o">=</span> <span class="o">-</span><span class="mi">4</span><span class="p">,</span>
  <span class="n">tok_number</span> <span class="o">=</span> <span class="o">-</span><span class="mi">5</span><span class="p">,</span>

  <span class="c1">// control</span>
  <span class="n">tok_if</span> <span class="o">=</span> <span class="o">-</span><span class="mi">6</span><span class="p">,</span>
  <span class="n">tok_then</span> <span class="o">=</span> <span class="o">-</span><span class="mi">7</span><span class="p">,</span>
  <span class="n">tok_else</span> <span class="o">=</span> <span class="o">-</span><span class="mi">8</span><span class="p">,</span>
  <span class="n">tok_for</span> <span class="o">=</span> <span class="o">-</span><span class="mi">9</span><span class="p">,</span>
  <span class="n">tok_in</span> <span class="o">=</span> <span class="o">-</span><span class="mi">10</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdentifierStr</span><span class="p">;</span> <span class="c1">// Filled in if tok_identifier</span>
<span class="k">static</span> <span class="kt">double</span> <span class="n">NumVal</span><span class="p">;</span>             <span class="c1">// Filled in if tok_number</span>

<span class="c1">/// gettok - Return the next token from standard input.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">gettok</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">static</span> <span class="kt">int</span> <span class="n">LastChar</span> <span class="o">=</span> <span class="sc">&#39; &#39;</span><span class="p">;</span>

  <span class="c1">// Skip any whitespace.</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">isspace</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span>
    <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">isalpha</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span> <span class="p">{</span> <span class="c1">// identifier: [a-zA-Z][a-zA-Z0-9]*</span>
    <span class="n">IdentifierStr</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">isalnum</span><span class="p">((</span><span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">())))</span>
      <span class="n">IdentifierStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;def&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_def</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;extern&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_extern</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;if&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_if</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;then&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_then</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;else&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_else</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;for&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_for</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;in&quot;</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">tok_in</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">tok_identifier</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// Number: [0-9.]+</span>
    <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">NumStr</span><span class="p">;</span>
    <span class="k">do</span> <span class="p">{</span>
      <span class="n">NumStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>
      <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
    <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">);</span>

    <span class="n">NumVal</span> <span class="o">=</span> <span class="n">strtod</span><span class="p">(</span><span class="n">NumStr</span><span class="p">.</span><span class="n">c_str</span><span class="p">(),</span> <span class="mi">0</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">tok_number</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;#&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Comment until end of line.</span>
    <span class="k">do</span>
      <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\n&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\r&#39;</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">gettok</span><span class="p">();</span>
  <span class="p">}</span>

  <span class="c1">// Check for end of file.  Don&#39;t eat the EOF.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="n">EOF</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">tok_eof</span><span class="p">;</span>

  <span class="c1">// Otherwise, just return the character as its ascii value.</span>
  <span class="kt">int</span> <span class="n">ThisChar</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
  <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
  <span class="k">return</span> <span class="n">ThisChar</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Abstract Syntax Tree (aka Parse Tree)</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="k">namespace</span> <span class="p">{</span>
<span class="c1">/// ExprAST - Base class for all expression nodes.</span>
<span class="k">class</span> <span class="nc">ExprAST</span> <span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">ExprAST</span><span class="p">()</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// NumberExprAST - Expression class for numeric literals like &quot;1.0&quot;.</span>
<span class="k">class</span> <span class="nc">NumberExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">double</span> <span class="n">Val</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">NumberExprAST</span><span class="p">(</span><span class="kt">double</span> <span class="n">val</span><span class="p">)</span> <span class="o">:</span> <span class="n">Val</span><span class="p">(</span><span class="n">val</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// VariableExprAST - Expression class for referencing a variable, like &quot;a&quot;.</span>
<span class="k">class</span> <span class="nc">VariableExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Name</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">VariableExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">name</span><span class="p">)</span> <span class="o">:</span> <span class="n">Name</span><span class="p">(</span><span class="n">name</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// BinaryExprAST - Expression class for a binary operator.</span>
<span class="k">class</span> <span class="nc">BinaryExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">char</span> <span class="n">Op</span><span class="p">;</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">LHS</span><span class="p">,</span> <span class="o">*</span><span class="n">RHS</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">BinaryExprAST</span><span class="p">(</span><span class="kt">char</span> <span class="n">op</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">lhs</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">rhs</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Op</span><span class="p">(</span><span class="n">op</span><span class="p">),</span> <span class="n">LHS</span><span class="p">(</span><span class="n">lhs</span><span class="p">),</span> <span class="n">RHS</span><span class="p">(</span><span class="n">rhs</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// CallExprAST - Expression class for function calls.</span>
<span class="k">class</span> <span class="nc">CallExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Callee</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">ExprAST</span> <span class="o">*&gt;</span> <span class="n">Args</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">CallExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">callee</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">ExprAST</span> <span class="o">*&gt;</span> <span class="o">&amp;</span><span class="n">args</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Callee</span><span class="p">(</span><span class="n">callee</span><span class="p">),</span> <span class="n">Args</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// IfExprAST - Expression class for if/then/else.</span>
<span class="k">class</span> <span class="nc">IfExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Cond</span><span class="p">,</span> <span class="o">*</span><span class="n">Then</span><span class="p">,</span> <span class="o">*</span><span class="n">Else</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">IfExprAST</span><span class="p">(</span><span class="n">ExprAST</span> <span class="o">*</span><span class="n">cond</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">then</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">_else</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Cond</span><span class="p">(</span><span class="n">cond</span><span class="p">),</span> <span class="n">Then</span><span class="p">(</span><span class="n">then</span><span class="p">),</span> <span class="n">Else</span><span class="p">(</span><span class="n">_else</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// ForExprAST - Expression class for for/in.</span>
<span class="k">class</span> <span class="nc">ForExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">VarName</span><span class="p">;</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Start</span><span class="p">,</span> <span class="o">*</span><span class="n">End</span><span class="p">,</span> <span class="o">*</span><span class="n">Step</span><span class="p">,</span> <span class="o">*</span><span class="n">Body</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">ForExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">varname</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">start</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">end</span><span class="p">,</span>
             <span class="n">ExprAST</span> <span class="o">*</span><span class="n">step</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">body</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">VarName</span><span class="p">(</span><span class="n">varname</span><span class="p">),</span> <span class="n">Start</span><span class="p">(</span><span class="n">start</span><span class="p">),</span> <span class="n">End</span><span class="p">(</span><span class="n">end</span><span class="p">),</span> <span class="n">Step</span><span class="p">(</span><span class="n">step</span><span class="p">),</span> <span class="n">Body</span><span class="p">(</span><span class="n">body</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// PrototypeAST - This class represents the &quot;prototype&quot; for a function,</span>
<span class="c1">/// which captures its name, and its argument names (thus implicitly the number</span>
<span class="c1">/// of arguments the function takes).</span>
<span class="k">class</span> <span class="nc">PrototypeAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Name</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="n">Args</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">PrototypeAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">name</span><span class="p">,</span> <span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="o">&amp;</span><span class="n">args</span><span class="p">)</span>
      <span class="o">:</span> <span class="n">Name</span><span class="p">(</span><span class="n">name</span><span class="p">),</span> <span class="n">Args</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="p">{}</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">();</span>
<span class="p">};</span>

<span class="c1">/// FunctionAST - This class represents a function definition itself.</span>
<span class="k">class</span> <span class="nc">FunctionAST</span> <span class="p">{</span>
  <span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">Proto</span><span class="p">;</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Body</span><span class="p">;</span>

<span class="k">public</span><span class="o">:</span>
  <span class="n">FunctionAST</span><span class="p">(</span><span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">proto</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">body</span><span class="p">)</span> <span class="o">:</span> <span class="n">Proto</span><span class="p">(</span><span class="n">proto</span><span class="p">),</span> <span class="n">Body</span><span class="p">(</span><span class="n">body</span><span class="p">)</span> <span class="p">{}</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">();</span>
<span class="p">};</span>
<span class="p">}</span> <span class="c1">// end anonymous namespace</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Parser</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current</span>
<span class="c1">/// token the parser is looking at.  getNextToken reads another token from the</span>
<span class="c1">/// lexer and updates CurTok with its results.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="n">CurTok</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">getNextToken</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="n">CurTok</span> <span class="o">=</span> <span class="n">gettok</span><span class="p">();</span> <span class="p">}</span>

<span class="c1">/// BinopPrecedence - This holds the precedence for each binary operator that is</span>
<span class="c1">/// defined.</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="kt">char</span><span class="p">,</span> <span class="kt">int</span><span class="o">&gt;</span> <span class="n">BinopPrecedence</span><span class="p">;</span>

<span class="c1">/// GetTokPrecedence - Get the precedence of the pending binary operator token.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">GetTokPrecedence</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isascii</span><span class="p">(</span><span class="n">CurTok</span><span class="p">))</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>

  <span class="c1">// Make sure it&#39;s a declared binop.</span>
  <span class="kt">int</span> <span class="n">TokPrec</span> <span class="o">=</span> <span class="n">BinopPrecedence</span><span class="p">[</span><span class="n">CurTok</span><span class="p">];</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">TokPrec</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// Error* - These are little helper functions for error handling.</span>
<span class="n">ExprAST</span> <span class="o">*</span><span class="nf">Error</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Error: %s</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="n">PrototypeAST</span> <span class="o">*</span><span class="nf">ErrorP</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">Error</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="n">FunctionAST</span> <span class="o">*</span><span class="nf">ErrorF</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">Error</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseExpression</span><span class="p">();</span>

<span class="c1">/// identifierexpr</span>
<span class="c1">///   ::= identifier</span>
<span class="c1">///   ::= identifier &#39;(&#39; expression* &#39;)&#39;</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseIdentifierExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>

  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat identifier.</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;(&#39;</span><span class="p">)</span> <span class="c1">// Simple variable ref.</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">VariableExprAST</span><span class="p">(</span><span class="n">IdName</span><span class="p">);</span>

  <span class="c1">// Call.</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat (</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">ExprAST</span> <span class="o">*&gt;</span> <span class="n">Args</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
      <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Arg</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
      <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">Arg</span><span class="p">)</span>
        <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
      <span class="n">Args</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">Arg</span><span class="p">);</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">==</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
        <span class="k">break</span><span class="p">;</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;,&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;Expected &#39;)&#39; or &#39;,&#39; in argument list&quot;</span><span class="p">);</span>
      <span class="n">getNextToken</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="c1">// Eat the &#39;)&#39;.</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="k">return</span> <span class="k">new</span> <span class="n">CallExprAST</span><span class="p">(</span><span class="n">IdName</span><span class="p">,</span> <span class="n">Args</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// numberexpr ::= number</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseNumberExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Result</span> <span class="o">=</span> <span class="k">new</span> <span class="n">NumberExprAST</span><span class="p">(</span><span class="n">NumVal</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// consume the number</span>
  <span class="k">return</span> <span class="n">Result</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// parenexpr ::= &#39;(&#39; expression &#39;)&#39;</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseParenExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat (.</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">V</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">V</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;)&#39;&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat ).</span>
  <span class="k">return</span> <span class="n">V</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// ifexpr ::= &#39;if&#39; expression &#39;then&#39; expression &#39;else&#39; expression</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseIfExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat the if.</span>

  <span class="c1">// condition.</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Cond</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">Cond</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_then</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected then&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat the then</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Then</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Then</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_else</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected else&quot;</span><span class="p">);</span>

  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Else</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">Else</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">return</span> <span class="k">new</span> <span class="n">IfExprAST</span><span class="p">(</span><span class="n">Cond</span><span class="p">,</span> <span class="n">Then</span><span class="p">,</span> <span class="n">Else</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// forexpr ::= &#39;for&#39; identifier &#39;=&#39; expr &#39;,&#39; expr (&#39;,&#39; expr)? &#39;in&#39; expression</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseForExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat the for.</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected identifier after for&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat identifier.</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;=&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;=&#39; after for&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat &#39;=&#39;.</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Start</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Start</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;,&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;,&#39; after for start value&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">End</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">End</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// The step value is optional.</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Step</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">==</span> <span class="sc">&#39;,&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">getNextToken</span><span class="p">();</span>
    <span class="n">Step</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Step</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_in</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;in&#39; after for&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat &#39;in&#39;.</span>

  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Body</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Body</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">return</span> <span class="k">new</span> <span class="n">ForExprAST</span><span class="p">(</span><span class="n">IdName</span><span class="p">,</span> <span class="n">Start</span><span class="p">,</span> <span class="n">End</span><span class="p">,</span> <span class="n">Step</span><span class="p">,</span> <span class="n">Body</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// primary</span>
<span class="c1">///   ::= identifierexpr</span>
<span class="c1">///   ::= numberexpr</span>
<span class="c1">///   ::= parenexpr</span>
<span class="c1">///   ::= ifexpr</span>
<span class="c1">///   ::= forexpr</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParsePrimary</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">switch</span> <span class="p">(</span><span class="n">CurTok</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">default</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;unknown token when expecting an expression&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="nl">tok_identifier</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">ParseIdentifierExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="nl">tok_number</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">ParseNumberExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="sc">&#39;(&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">ParseParenExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="nl">tok_if</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">ParseIfExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="nl">tok_for</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">ParseForExpr</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// binoprhs</span>
<span class="c1">///   ::= (&#39;+&#39; primary)*</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseBinOpRHS</span><span class="p">(</span><span class="kt">int</span> <span class="n">ExprPrec</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">LHS</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// If this is a binop, find its precedence.</span>
  <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">TokPrec</span> <span class="o">=</span> <span class="n">GetTokPrecedence</span><span class="p">();</span>

    <span class="c1">// If this is a binop that binds at least as tightly as the current binop,</span>
    <span class="c1">// consume it, otherwise we are done.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;</span> <span class="n">ExprPrec</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">LHS</span><span class="p">;</span>

    <span class="c1">// Okay, we know this is a binop.</span>
    <span class="kt">int</span> <span class="n">BinOp</span> <span class="o">=</span> <span class="n">CurTok</span><span class="p">;</span>
    <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat binop</span>

    <span class="c1">// Parse the primary expression after the binary operator.</span>
    <span class="n">ExprAST</span> <span class="o">*</span><span class="n">RHS</span> <span class="o">=</span> <span class="n">ParsePrimary</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">RHS</span><span class="p">)</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

    <span class="c1">// If BinOp binds less tightly with RHS than the operator after RHS, let</span>
    <span class="c1">// the pending operator take RHS as its LHS.</span>
    <span class="kt">int</span> <span class="n">NextPrec</span> <span class="o">=</span> <span class="n">GetTokPrecedence</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;</span> <span class="n">NextPrec</span><span class="p">)</span> <span class="p">{</span>
      <span class="n">RHS</span> <span class="o">=</span> <span class="n">ParseBinOpRHS</span><span class="p">(</span><span class="n">TokPrec</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">RHS</span><span class="p">);</span>
      <span class="k">if</span> <span class="p">(</span><span class="n">RHS</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// Merge LHS/RHS.</span>
    <span class="n">LHS</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BinaryExprAST</span><span class="p">(</span><span class="n">BinOp</span><span class="p">,</span> <span class="n">LHS</span><span class="p">,</span> <span class="n">RHS</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// expression</span>
<span class="c1">///   ::= primary binoprhs</span>
<span class="c1">///</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseExpression</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">LHS</span> <span class="o">=</span> <span class="n">ParsePrimary</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">LHS</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">return</span> <span class="n">ParseBinOpRHS</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">LHS</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// prototype</span>
<span class="c1">///   ::= id &#39;(&#39; id* &#39;)&#39;</span>
<span class="k">static</span> <span class="n">PrototypeAST</span> <span class="o">*</span><span class="nf">ParsePrototype</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorP</span><span class="p">(</span><span class="s">&quot;Expected function name in prototype&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">FnName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;(&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorP</span><span class="p">(</span><span class="s">&quot;Expected &#39;(&#39; in prototype&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="n">ArgNames</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">getNextToken</span><span class="p">()</span> <span class="o">==</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="n">ArgNames</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">IdentifierStr</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorP</span><span class="p">(</span><span class="s">&quot;Expected &#39;)&#39; in prototype&quot;</span><span class="p">);</span>

  <span class="c1">// success.</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat &#39;)&#39;.</span>

  <span class="k">return</span> <span class="k">new</span> <span class="n">PrototypeAST</span><span class="p">(</span><span class="n">FnName</span><span class="p">,</span> <span class="n">ArgNames</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// definition ::= &#39;def&#39; prototype expression</span>
<span class="k">static</span> <span class="n">FunctionAST</span> <span class="o">*</span><span class="nf">ParseDefinition</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat def.</span>
  <span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">Proto</span> <span class="o">=</span> <span class="n">ParsePrototype</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Proto</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">ExprAST</span> <span class="o">*</span><span class="n">E</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">())</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">FunctionAST</span><span class="p">(</span><span class="n">Proto</span><span class="p">,</span> <span class="n">E</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// toplevelexpr ::= expression</span>
<span class="k">static</span> <span class="n">FunctionAST</span> <span class="o">*</span><span class="nf">ParseTopLevelExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">ExprAST</span> <span class="o">*</span><span class="n">E</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">())</span> <span class="p">{</span>
    <span class="c1">// Make an anonymous proto.</span>
    <span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">Proto</span> <span class="o">=</span> <span class="k">new</span> <span class="n">PrototypeAST</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span><span class="p">());</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">FunctionAST</span><span class="p">(</span><span class="n">Proto</span><span class="p">,</span> <span class="n">E</span><span class="p">);</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// external ::= &#39;extern&#39; prototype</span>
<span class="k">static</span> <span class="n">PrototypeAST</span> <span class="o">*</span><span class="nf">ParseExtern</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// eat extern.</span>
  <span class="k">return</span> <span class="n">ParsePrototype</span><span class="p">();</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Code Generation</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="k">static</span> <span class="n">Module</span> <span class="o">*</span><span class="n">TheModule</span><span class="p">;</span>
<span class="k">static</span> <span class="n">IRBuilder</span><span class="o">&lt;&gt;</span> <span class="n">Builder</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">());</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="p">,</span> <span class="n">Value</span> <span class="o">*&gt;</span> <span class="n">NamedValues</span><span class="p">;</span>
<span class="k">static</span> <span class="n">legacy</span><span class="o">::</span><span class="n">FunctionPassManager</span> <span class="o">*</span><span class="n">TheFPM</span><span class="p">;</span>

<span class="n">Value</span> <span class="o">*</span><span class="nf">ErrorV</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">Error</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">NumberExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="n">Val</span><span class="p">));</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">VariableExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look this variable up in the function.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">V</span> <span class="o">=</span> <span class="n">NamedValues</span><span class="p">[</span><span class="n">Name</span><span class="p">];</span>
  <span class="k">return</span> <span class="n">V</span> <span class="o">?</span> <span class="nl">V</span> <span class="p">:</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Unknown variable name&quot;</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">BinaryExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">L</span> <span class="o">=</span> <span class="n">LHS</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">R</span> <span class="o">=</span> <span class="n">RHS</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">L</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">||</span> <span class="n">R</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">switch</span> <span class="p">(</span><span class="n">Op</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">case</span> <span class="sc">&#39;+&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFAdd</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;addtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;-&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFSub</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;subtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;*&#39;</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFMul</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;multmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;&lt;&#39;</span><span class="o">:</span>
    <span class="n">L</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpULT</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;cmptmp&quot;</span><span class="p">);</span>
    <span class="c1">// Convert bool 0/1 to double 0.0 or 1.0</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateUIToFP</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span>
                                <span class="s">&quot;booltmp&quot;</span><span class="p">);</span>
  <span class="k">default</span><span class="o">:</span>
    <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;invalid binary operator&quot;</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">CallExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look up the name in the global module table.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">CalleeF</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Callee</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Unknown function referenced&quot;</span><span class="p">);</span>

  <span class="c1">// If argument mismatch error.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Incorrect # arguments passed&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Value</span> <span class="o">*&gt;</span> <span class="n">ArgsV</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span> <span class="n">i</span> <span class="o">!=</span> <span class="n">e</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">ArgsV</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">());</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">ArgsV</span><span class="p">.</span><span class="n">back</span><span class="p">()</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateCall</span><span class="p">(</span><span class="n">CalleeF</span><span class="p">,</span> <span class="n">ArgsV</span><span class="p">,</span> <span class="s">&quot;calltmp&quot;</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">IfExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">CondV</span> <span class="o">=</span> <span class="n">Cond</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CondV</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// Convert condition to a bool by comparing equal to 0.0.</span>
  <span class="n">CondV</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpONE</span><span class="p">(</span>
      <span class="n">CondV</span><span class="p">,</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="mf">0.0</span><span class="p">)),</span> <span class="s">&quot;ifcond&quot;</span><span class="p">);</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">()</span><span class="o">-&gt;</span><span class="n">getParent</span><span class="p">();</span>

  <span class="c1">// Create blocks for the then and else cases.  Insert the &#39;then&#39; block at the</span>
  <span class="c1">// end of the function.</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">ThenBB</span> <span class="o">=</span>
      <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;then&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">ElseBB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;else&quot;</span><span class="p">);</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">MergeBB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;ifcont&quot;</span><span class="p">);</span>

  <span class="n">Builder</span><span class="p">.</span><span class="n">CreateCondBr</span><span class="p">(</span><span class="n">CondV</span><span class="p">,</span> <span class="n">ThenBB</span><span class="p">,</span> <span class="n">ElseBB</span><span class="p">);</span>

  <span class="c1">// Emit then value.</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">ThenBB</span><span class="p">);</span>

  <span class="n">Value</span> <span class="o">*</span><span class="n">ThenV</span> <span class="o">=</span> <span class="n">Then</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">ThenV</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="n">Builder</span><span class="p">.</span><span class="n">CreateBr</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
  <span class="c1">// Codegen of &#39;Then&#39; can change the current block, update ThenBB for the PHI.</span>
  <span class="n">ThenBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>

  <span class="c1">// Emit else block.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">getBasicBlockList</span><span class="p">().</span><span class="n">push_back</span><span class="p">(</span><span class="n">ElseBB</span><span class="p">);</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">ElseBB</span><span class="p">);</span>

  <span class="n">Value</span> <span class="o">*</span><span class="n">ElseV</span> <span class="o">=</span> <span class="n">Else</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">ElseV</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="n">Builder</span><span class="p">.</span><span class="n">CreateBr</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
  <span class="c1">// Codegen of &#39;Else&#39; can change the current block, update ElseBB for the PHI.</span>
  <span class="n">ElseBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>

  <span class="c1">// Emit merge block.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">getBasicBlockList</span><span class="p">().</span><span class="n">push_back</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">MergeBB</span><span class="p">);</span>
  <span class="n">PHINode</span> <span class="o">*</span><span class="n">PN</span> <span class="o">=</span>
      <span class="n">Builder</span><span class="p">.</span><span class="n">CreatePHI</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span> <span class="mi">2</span><span class="p">,</span> <span class="s">&quot;iftmp&quot;</span><span class="p">);</span>

  <span class="n">PN</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">ThenV</span><span class="p">,</span> <span class="n">ThenBB</span><span class="p">);</span>
  <span class="n">PN</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">ElseV</span><span class="p">,</span> <span class="n">ElseBB</span><span class="p">);</span>
  <span class="k">return</span> <span class="n">PN</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">ForExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Output this as:</span>
  <span class="c1">//   ...</span>
  <span class="c1">//   start = startexpr</span>
  <span class="c1">//   goto loop</span>
  <span class="c1">// loop:</span>
  <span class="c1">//   variable = phi [start, loopheader], [nextvariable, loopend]</span>
  <span class="c1">//   ...</span>
  <span class="c1">//   bodyexpr</span>
  <span class="c1">//   ...</span>
  <span class="c1">// loopend:</span>
  <span class="c1">//   step = stepexpr</span>
  <span class="c1">//   nextvariable = variable + step</span>
  <span class="c1">//   endcond = endexpr</span>
  <span class="c1">//   br endcond, loop, endloop</span>
  <span class="c1">// outloop:</span>

  <span class="c1">// Emit the start code first, without &#39;variable&#39; in scope.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">StartVal</span> <span class="o">=</span> <span class="n">Start</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">StartVal</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// Make the new basic block for the loop header, inserting after current</span>
  <span class="c1">// block.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">()</span><span class="o">-&gt;</span><span class="n">getParent</span><span class="p">();</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">PreheaderBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">LoopBB</span> <span class="o">=</span>
      <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;loop&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>

  <span class="c1">// Insert an explicit fall through from the current block to the LoopBB.</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">CreateBr</span><span class="p">(</span><span class="n">LoopBB</span><span class="p">);</span>

  <span class="c1">// Start insertion in LoopBB.</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">LoopBB</span><span class="p">);</span>

  <span class="c1">// Start the PHI node with an entry for Start.</span>
  <span class="n">PHINode</span> <span class="o">*</span><span class="n">Variable</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreatePHI</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span>
                                        <span class="mi">2</span><span class="p">,</span> <span class="n">VarName</span><span class="p">.</span><span class="n">c_str</span><span class="p">());</span>
  <span class="n">Variable</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">StartVal</span><span class="p">,</span> <span class="n">PreheaderBB</span><span class="p">);</span>

  <span class="c1">// Within the loop, the variable is defined equal to the PHI node.  If it</span>
  <span class="c1">// shadows an existing variable, we have to restore it, so save it now.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">OldVal</span> <span class="o">=</span> <span class="n">NamedValues</span><span class="p">[</span><span class="n">VarName</span><span class="p">];</span>
  <span class="n">NamedValues</span><span class="p">[</span><span class="n">VarName</span><span class="p">]</span> <span class="o">=</span> <span class="n">Variable</span><span class="p">;</span>

  <span class="c1">// Emit the body of the loop.  This, like any other expr, can change the</span>
  <span class="c1">// current BB.  Note that we ignore the value computed by the body, but don&#39;t</span>
  <span class="c1">// allow an error.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Body</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">()</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// Emit the step value.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">StepVal</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Step</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">StepVal</span> <span class="o">=</span> <span class="n">Step</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">StepVal</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// If not specified, use 1.0.</span>
    <span class="n">StepVal</span> <span class="o">=</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="mf">1.0</span><span class="p">));</span>
  <span class="p">}</span>

  <span class="n">Value</span> <span class="o">*</span><span class="n">NextVar</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFAdd</span><span class="p">(</span><span class="n">Variable</span><span class="p">,</span> <span class="n">StepVal</span><span class="p">,</span> <span class="s">&quot;nextvar&quot;</span><span class="p">);</span>

  <span class="c1">// Compute the end condition.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">EndCond</span> <span class="o">=</span> <span class="n">End</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">EndCond</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">EndCond</span><span class="p">;</span>

  <span class="c1">// Convert condition to a bool by comparing equal to 0.0.</span>
  <span class="n">EndCond</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpONE</span><span class="p">(</span>
      <span class="n">EndCond</span><span class="p">,</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="mf">0.0</span><span class="p">)),</span> <span class="s">&quot;loopcond&quot;</span><span class="p">);</span>

  <span class="c1">// Create the &quot;after loop&quot; block and insert it.</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">LoopEndBB</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">GetInsertBlock</span><span class="p">();</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">AfterBB</span> <span class="o">=</span>
      <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;afterloop&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>

  <span class="c1">// Insert the conditional branch into the end of LoopEndBB.</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">CreateCondBr</span><span class="p">(</span><span class="n">EndCond</span><span class="p">,</span> <span class="n">LoopBB</span><span class="p">,</span> <span class="n">AfterBB</span><span class="p">);</span>

  <span class="c1">// Any new code will be inserted in AfterBB.</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">AfterBB</span><span class="p">);</span>

  <span class="c1">// Add a new entry to the PHI node for the backedge.</span>
  <span class="n">Variable</span><span class="o">-&gt;</span><span class="n">addIncoming</span><span class="p">(</span><span class="n">NextVar</span><span class="p">,</span> <span class="n">LoopEndBB</span><span class="p">);</span>

  <span class="c1">// Restore the unshadowed variable.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">OldVal</span><span class="p">)</span>
    <span class="n">NamedValues</span><span class="p">[</span><span class="n">VarName</span><span class="p">]</span> <span class="o">=</span> <span class="n">OldVal</span><span class="p">;</span>
  <span class="k">else</span>
    <span class="n">NamedValues</span><span class="p">.</span><span class="n">erase</span><span class="p">(</span><span class="n">VarName</span><span class="p">);</span>

  <span class="c1">// for expr always returns 0.0.</span>
  <span class="k">return</span> <span class="n">Constant</span><span class="o">::</span><span class="n">getNullValue</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()));</span>
<span class="p">}</span>

<span class="n">Function</span> <span class="o">*</span><span class="n">PrototypeAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Make the function type:  double(double,double) etc.</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Type</span> <span class="o">*&gt;</span> <span class="n">Doubles</span><span class="p">(</span><span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">(),</span>
                              <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()));</span>
  <span class="n">FunctionType</span> <span class="o">*</span><span class="n">FT</span> <span class="o">=</span>
      <span class="n">FunctionType</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span> <span class="n">Doubles</span><span class="p">,</span> <span class="nb">false</span><span class="p">);</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span>
      <span class="n">Function</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">FT</span><span class="p">,</span> <span class="n">Function</span><span class="o">::</span><span class="n">ExternalLinkage</span><span class="p">,</span> <span class="n">Name</span><span class="p">,</span> <span class="n">TheModule</span><span class="p">);</span>

  <span class="c1">// If F conflicted, there was already something named &#39;Name&#39;.  If it has a</span>
  <span class="c1">// body, don&#39;t allow redefinition or reextern.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">getName</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Name</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Delete the one we just made and get the existing one.</span>
    <span class="n">F</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
    <span class="n">F</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Name</span><span class="p">);</span>

    <span class="c1">// If F already has a body, reject this.</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">ErrorF</span><span class="p">(</span><span class="s">&quot;redefinition of function&quot;</span><span class="p">);</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1">// If F took a different number of args, reject.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">ErrorF</span><span class="p">(</span><span class="s">&quot;redefinition of function with different # args&quot;</span><span class="p">);</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="c1">// Set names for all arguments.</span>
  <span class="kt">unsigned</span> <span class="n">Idx</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="n">Function</span><span class="o">::</span><span class="n">arg_iterator</span> <span class="n">AI</span> <span class="o">=</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">arg_begin</span><span class="p">();</span> <span class="n">Idx</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span>
       <span class="o">++</span><span class="n">AI</span><span class="p">,</span> <span class="o">++</span><span class="n">Idx</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">AI</span><span class="o">-&gt;</span><span class="n">setName</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="p">]);</span>

    <span class="c1">// Add arguments to variable symbol table.</span>
    <span class="n">NamedValues</span><span class="p">[</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="p">]]</span> <span class="o">=</span> <span class="n">AI</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">F</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">Function</span> <span class="o">*</span><span class="n">FunctionAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">NamedValues</span><span class="p">.</span><span class="n">clear</span><span class="p">();</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Proto</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">TheFunction</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// Create a new basic block to start insertion into.</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">BB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;entry&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">BB</span><span class="p">);</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">Value</span> <span class="o">*</span><span class="n">RetVal</span> <span class="o">=</span> <span class="n">Body</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
    <span class="c1">// Finish off the function.</span>
    <span class="n">Builder</span><span class="p">.</span><span class="n">CreateRet</span><span class="p">(</span><span class="n">RetVal</span><span class="p">);</span>

    <span class="c1">// Validate the generated code, checking for consistency.</span>
    <span class="n">verifyFunction</span><span class="p">(</span><span class="o">*</span><span class="n">TheFunction</span><span class="p">);</span>

    <span class="c1">// Optimize the function.</span>
    <span class="n">TheFPM</span><span class="o">-&gt;</span><span class="n">run</span><span class="p">(</span><span class="o">*</span><span class="n">TheFunction</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">TheFunction</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="c1">// Error reading body, remove function.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Top-Level parsing and JIT Driver</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="k">static</span> <span class="n">ExecutionEngine</span> <span class="o">*</span><span class="n">TheExecutionEngine</span><span class="p">;</span>

<span class="k">static</span> <span class="kt">void</span> <span class="nf">HandleDefinition</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">FunctionAST</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">ParseDefinition</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Function</span> <span class="o">*</span><span class="n">LF</span> <span class="o">=</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read function definition:&quot;</span><span class="p">);</span>
      <span class="n">LF</span><span class="o">-&gt;</span><span class="n">dump</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="nf">HandleExtern</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">P</span> <span class="o">=</span> <span class="n">ParseExtern</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Function</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">P</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read extern: &quot;</span><span class="p">);</span>
      <span class="n">F</span><span class="o">-&gt;</span><span class="n">dump</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="nf">HandleTopLevelExpression</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Evaluate a top-level expression into an anonymous function.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">FunctionAST</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">ParseTopLevelExpr</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Function</span> <span class="o">*</span><span class="n">LF</span> <span class="o">=</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">TheExecutionEngine</span><span class="o">-&gt;</span><span class="n">finalizeObject</span><span class="p">();</span>
      <span class="c1">// JIT the function, returning a function pointer.</span>
      <span class="kt">void</span> <span class="o">*</span><span class="n">FPtr</span> <span class="o">=</span> <span class="n">TheExecutionEngine</span><span class="o">-&gt;</span><span class="n">getPointerToFunction</span><span class="p">(</span><span class="n">LF</span><span class="p">);</span>

      <span class="c1">// Cast it to the right type (takes no arguments, returns a double) so we</span>
      <span class="c1">// can call it as a native function.</span>
      <span class="kt">double</span> <span class="p">(</span><span class="o">*</span><span class="n">FP</span><span class="p">)()</span> <span class="o">=</span> <span class="p">(</span><span class="kt">double</span> <span class="p">(</span><span class="o">*</span><span class="p">)())(</span><span class="kt">intptr_t</span><span class="p">)</span><span class="n">FPtr</span><span class="p">;</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Evaluated to %f</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">FP</span><span class="p">());</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// top ::= definition | external | expression | &#39;;&#39;</span>
<span class="k">static</span> <span class="kt">void</span> <span class="nf">MainLoop</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;ready&gt; &quot;</span><span class="p">);</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">CurTok</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">case</span> <span class="nl">tok_eof</span><span class="p">:</span>
      <span class="k">return</span><span class="p">;</span>
    <span class="k">case</span> <span class="sc">&#39;;&#39;</span><span class="o">:</span>
      <span class="n">getNextToken</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span> <span class="c1">// ignore top-level semicolons.</span>
    <span class="k">case</span> <span class="nl">tok_def</span><span class="p">:</span>
      <span class="n">HandleDefinition</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="k">case</span> <span class="nl">tok_extern</span><span class="p">:</span>
      <span class="n">HandleExtern</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="k">default</span><span class="o">:</span>
      <span class="n">HandleTopLevelExpression</span><span class="p">();</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// &quot;Library&quot; functions that can be &quot;extern&#39;d&quot; from user code.</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">/// putchard - putchar that takes a double and returns 0.</span>
<span class="k">extern</span> <span class="s">&quot;C&quot;</span> <span class="kt">double</span> <span class="n">putchard</span><span class="p">(</span><span class="kt">double</span> <span class="n">X</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">putchar</span><span class="p">((</span><span class="kt">char</span><span class="p">)</span><span class="n">X</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Main driver code.</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="kt">int</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">InitializeNativeTarget</span><span class="p">();</span>
  <span class="n">InitializeNativeTargetAsmPrinter</span><span class="p">();</span>
  <span class="n">InitializeNativeTargetAsmParser</span><span class="p">();</span>
  <span class="n">LLVMContext</span> <span class="o">&amp;</span><span class="n">Context</span> <span class="o">=</span> <span class="n">getGlobalContext</span><span class="p">();</span>

  <span class="c1">// Install standard binary operators.</span>
  <span class="c1">// 1 is lowest precedence.</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;&lt;&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">10</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;+&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;-&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;*&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">40</span><span class="p">;</span> <span class="c1">// highest.</span>

  <span class="c1">// Prime the first token.</span>
  <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;ready&gt; &quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="c1">// Make the module, which holds all the code.</span>
  <span class="n">std</span><span class="o">::</span><span class="n">unique_ptr</span><span class="o">&lt;</span><span class="n">Module</span><span class="o">&gt;</span> <span class="n">Owner</span> <span class="o">=</span> <span class="n">make_unique</span><span class="o">&lt;</span><span class="n">Module</span><span class="o">&gt;</span><span class="p">(</span><span class="s">&quot;my cool jit&quot;</span><span class="p">,</span> <span class="n">Context</span><span class="p">);</span>
  <span class="n">TheModule</span> <span class="o">=</span> <span class="n">Owner</span><span class="p">.</span><span class="n">get</span><span class="p">();</span>

  <span class="c1">// Create the JIT.  This takes ownership of the module.</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">ErrStr</span><span class="p">;</span>
  <span class="n">TheExecutionEngine</span> <span class="o">=</span>
      <span class="n">EngineBuilder</span><span class="p">(</span><span class="n">std</span><span class="o">::</span><span class="n">move</span><span class="p">(</span><span class="n">Owner</span><span class="p">))</span>
          <span class="p">.</span><span class="n">setErrorStr</span><span class="p">(</span><span class="o">&amp;</span><span class="n">ErrStr</span><span class="p">)</span>
          <span class="p">.</span><span class="n">setMCJITMemoryManager</span><span class="p">(</span><span class="n">llvm</span><span class="o">::</span><span class="n">make_unique</span><span class="o">&lt;</span><span class="n">SectionMemoryManager</span><span class="o">&gt;</span><span class="p">())</span>
          <span class="p">.</span><span class="n">create</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">TheExecutionEngine</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Could not create ExecutionEngine: %s</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">ErrStr</span><span class="p">.</span><span class="n">c_str</span><span class="p">());</span>
    <span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="n">legacy</span><span class="o">::</span><span class="n">FunctionPassManager</span> <span class="n">OurFPM</span><span class="p">(</span><span class="n">TheModule</span><span class="p">);</span>

  <span class="c1">// Set up the optimizer pipeline.  Start with registering info about how the</span>
  <span class="c1">// target lays out data structures.</span>
  <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">setDataLayout</span><span class="p">(</span><span class="o">*</span><span class="n">TheExecutionEngine</span><span class="o">-&gt;</span><span class="n">getDataLayout</span><span class="p">());</span>
  <span class="c1">// Provide basic AliasAnalysis support for GVN.</span>
  <span class="n">OurFPM</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">createBasicAliasAnalysisPass</span><span class="p">());</span>
  <span class="c1">// Do simple &quot;peephole&quot; optimizations and bit-twiddling optzns.</span>
  <span class="n">OurFPM</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">createInstructionCombiningPass</span><span class="p">());</span>
  <span class="c1">// Reassociate expressions.</span>
  <span class="n">OurFPM</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">createReassociatePass</span><span class="p">());</span>
  <span class="c1">// Eliminate Common SubExpressions.</span>
  <span class="n">OurFPM</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">createGVNPass</span><span class="p">());</span>
  <span class="c1">// Simplify the control flow graph (deleting unreachable blocks, etc).</span>
  <span class="n">OurFPM</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">createCFGSimplificationPass</span><span class="p">());</span>

  <span class="n">OurFPM</span><span class="p">.</span><span class="n">doInitialization</span><span class="p">();</span>

  <span class="c1">// Set the global so the code gen can use this.</span>
  <span class="n">TheFPM</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">OurFPM</span><span class="p">;</span>

  <span class="c1">// Run the main &quot;interpreter loop&quot; now.</span>
  <span class="n">MainLoop</span><span class="p">();</span>

  <span class="n">TheFPM</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// Print out all of the generated code.</span>
  <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">dump</span><span class="p">();</span>

  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p><a class="reference external" href="LangImpl6.html">Next: Extending the language: user-defined operators</a></p>
</div>
</div>


          </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="LangImpl6.html" title="6. Kaleidoscope: Extending the Language: User-defined Operators"
             >next</a> |</li>
        <li class="right" >
          <a href="LangImpl4.html" title="4. Kaleidoscope: Adding JIT and Optimizer Support"
             >previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" >LLVM Tutorial: Table of Contents</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &copy; Copyright 2003-2015, LLVM Project.
      Last updated on 2015-09-08.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1.
    </div>
  </body>
</html>